package com.karrysong.answerapplication.activities;



import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.karrysong.answerapplication.MyApplication;
import com.karrysong.answerapplication.R;
import com.karrysong.answerapplication.beans.Question;
import com.karrysong.answerapplication.beans.TK;
import com.karrysong.answerapplication.beans.User;
import com.karrysong.answerapplication.constants.SPkey;
import com.karrysong.answerapplication.utils.LogUtils;
import com.karrysong.answerapplication.utils.SPUtils;
import com.karrysong.answerapplication.utils.ToastUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;

public class MainActivity extends BaseActivity {

    @BindView(R.id.questionTypeSpinner)
    Spinner spinner;
    @BindView(R.id.allQuestion)
    TextView allQuestionView;
    @BindView(R.id.toVip)
    TextView toVipText;
    private int questionType = 10;
    private boolean userIsVip = false;
    private List<TK> tkList = new ArrayList<>();
    private ProgressDialog allProgress;
    boolean isOKVip, isokTK;
    private boolean isHaveQuestion;

    @Override
    int getLayoutId() {
        return R.layout.activity_main;
    }

    @OnClick({R.id.ll_main_start_answer, R.id.btn_choose, R.id.btn_judge, R.id.btn_blanks, R.id.btn_about, R.id.logout, R.id.toVip, R.id.user})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_main_start_answer:
                if (!isHaveQuestion){
                    ToastUtils.showLong("此题库无题目");
                    break;
                }
                //考试模式
                Intent intent = new Intent(MainActivity.this, AnswerActivity.class);
                intent.putExtra("questionType", questionType);
                intent.putExtra("type", 0);
                startActivity(intent);
                break;
            case R.id.btn_choose:
                if (!isHaveQuestion){
                    ToastUtils.showLong("此题库无题目");
                    break;
                }
                // 选择题
                Intent intent3 = new Intent(MainActivity.this, AnswerActivity.class);
                intent3.putExtra("type", 1);
                intent3.putExtra("questionType", questionType);
                startActivity(intent3);
                break;
            case R.id.btn_judge:
                if (!isHaveQuestion){
                    ToastUtils.showLong("此题库无题目");
                    break;
                }
                //  判断题
                Intent intent4 = new Intent(MainActivity.this, AnswerActivity.class);
                intent4.putExtra("type", 2);
                intent4.putExtra("questionType", questionType);
                startActivity(intent4);
                break;
            case R.id.btn_blanks:
                if (!isHaveQuestion){
                    ToastUtils.showLong("此题库无题目");
                    break;
                }
                // 简答题
                Intent intent5 = new Intent(MainActivity.this, AnswerActivity.class);
                intent5.putExtra("type", 3);
                intent5.putExtra("questionType", questionType);
                startActivity(intent5);
                break;
            case R.id.btn_about:
                //  关于
                Intent intent6 = new Intent(MainActivity.this, AboutActivity.class);
                startActivity(intent6);
                break;
            case R.id.logout:
                SPUtils.put(MainActivity.this, SPkey.UserName, null);
                SPUtils.remove(MainActivity.this, SPkey.UserName);
                startActivity(new Intent(this, LoginActivity.class));
                break;
            case R.id.user:
                startActivity(new Intent(MainActivity.this, UserActivity.class));
                break;
            case R.id.toVip:
                startActivity(new Intent(MainActivity.this, OpenVipActivity.class));
                break;
        }
    }

    @Override
    void initData() {
        super.initData();
        allProgress = new ProgressDialog(MainActivity.this, R.style.AppTheme_Dark_Dialog);
        allProgress.setIndeterminate(true);
        allProgress.setMessage("加载数据中...");
        allProgress.setCancelable(false);
        allProgress.show();

        BmobQuery<TK> tkBmobQuery = new BmobQuery<>();
        tkBmobQuery.findObjects(new FindListener<TK>() {
            @Override
            public void done(List<TK> list, BmobException e) {
                if (e == null && list != null){
                    LogUtils.i(list.size() + "");
                    Message message = new Message();
                    message.what = 1;
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("tk", (Serializable) list);
                    for (int i = 0; i < list.size(); i++) {
                        TK tk = list.get(i);
                        if (!tk.getVip()){
                            bundle.putInt("position", i);
                            break;
                        }
                    }
                    message.setData(bundle);
                    handler.sendMessage(message);
                }else if (e != null){
                    e.printStackTrace();
                }else {
                    LogUtils.i("111");
                }
            }
        });

        //初始化用户是否是会员
        BmobQuery<User> userBmobQuery = new BmobQuery<>();
        userBmobQuery.getObject((String) SPUtils.get(MainActivity.this, SPkey.ID, ""), new QueryListener<User>() {
            @Override
            public void done(User user, BmobException e) {
                if (e == null && user != null){
                    Message message = new Message();
                    message.what = 2;
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("vip", user.getIsVip());
                    message.setData(bundle);
                    handler.sendMessage(message);
                }else if (e != null){
                    e.printStackTrace();
                }else {
                    LogUtils.i("222");
                }
            }
        });


        SQLiteDatabase daoInstant = MyApplication.getDaoInstant();
        Cursor cursor = daoInstant.query("tb_question", null, "questionType = ?", new String[]{"" + questionType}, null, null, null);
        allQuestionView.setText("本题库共" + cursor.getCount() + "题");
        if (cursor.getCount() > 0){
            isHaveQuestion = true;
            LogUtils.i(1 + " true");
        }else {
            isHaveQuestion = false;
            LogUtils.i(1 + " false");
        }

    }

    private Handler handler = new Handler(Looper.myLooper()){

        @Override
        public void handleMessage(@NonNull Message msg) {
            LogUtils.i("333:" + msg.what);
            Bundle data = msg.getData();
            switch (msg.what){
                case 1:
                    List<TK> list = (List<TK>) data.get("tk");
                    int position = data.getInt("position");
                    tkList.addAll(new ArrayList<>(list));
                    List<Map<String, Object>> dataList = new ArrayList<>();
                    for (TK tk : list) {
                        LogUtils.i(tk.toString());
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", tk.getTk_number());
                        if (tk.getVip()){
                            map.put("vipInfo", "V");
                        }else {
                            map.put("vipInfo", "   ");
                        }
                        map.put("name", tk.getTk_name());
                        map.put("isVip", tk.getVip());
                        dataList.add(map);
                    }
                    SimpleAdapter adapter1 = new SimpleAdapter(MainActivity.this, dataList, R.layout.spinner_adapter, new String[]{"id", "name", "vipInfo"}, new int[]{R.id.areaId, R.id.name, R.id.vipView});
                    spinner.setAdapter(adapter1);
                    LogUtils.i(spinner.getCount() + "");
                    spinner.setSelection(position, true);
                    questionType = list.get(position).getTk_number();
                    SPUtils.put(MainActivity.this, "thisQuestionType", list.get(position).getTk_name());
                    isokTK = true;
                    if (isokTK && isOKVip){
                        allProgress.dismiss();
                        allProgress.cancel();
                        init();
                    }
                    break;
                case 2:
                    boolean vip = data.getBoolean("vip");
                    SPUtils.put(MainActivity.this, SPkey.IS_VIP, vip);
                    userIsVip = vip;
                    if (userIsVip){
                        toVipText.setText("欢迎VIP用户!!!");
                    }
                    isOKVip = true;
                    if (isokTK && isOKVip){
                        allProgress.dismiss();
                        allProgress.cancel();
                        init();
                    }
                    break;
            }
        }
    };

    void init(){
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Map<String, Object> itemAtPosition = (Map<String, Object>) parent.getItemAtPosition(position);
                SQLiteDatabase daoInstant = MyApplication.getDaoInstant();
                int id1 = (int) itemAtPosition.get("id");
                //新选中的questionType和之前一样则不变
                if (id1 == questionType){
                    return;
                }


                //若已经下载则删除已经下载的题目
                daoInstant.delete("tb_question", "questionType=?", new String[]{id1 + ""});
                //判断是否是会员题库
                boolean isVip = (boolean) itemAtPosition.get("isVip");
                if (isVip && !userIsVip){
                    //提示开通会员
                    new AlertDialog.Builder(MainActivity.this).setTitle("开通会员")
                            .setMessage("此题库是会员题库，您还不是会员，请先开通会员！")
                            .setPositiveButton("开通", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    startActivity(new Intent(MainActivity.this, OpenVipActivity.class));
                                }
                            }).setNegativeButton("取消", null)
                            .show();
                    for (int i = 0; i < tkList.size(); i++) {
                        TK tk = tkList.get(i);
                        if (tk.getTk_number() == questionType){
                            spinner.setSelection(i, true);
                        }
                    }
                    return;
                }

                //判断题库是否存在，若不存在则初始化题库
                questionType = id1;
                SPUtils.put(MainActivity.this, "thisQuestionType", itemAtPosition.get("name"));
                Cursor cursor = daoInstant.query("tb_question", null, "questionType = ?", new String[]{"" + id1}, null, null, null);
                //ToastUtils.showLong(position+"  " + cursor.getCount());
                if (cursor.getCount() <= 0){
                    //初始化题目
                    //进度条对话框
                    final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this, R.style.AppTheme_Dark_Dialog);
                    progressDialog.setIndeterminate(true);
                    progressDialog.setMessage("下载题库中...");
                    progressDialog.setCancelable(false);
                    progressDialog.show();

                    BmobQuery<Question> bmobQuery = new BmobQuery<>();
                    bmobQuery.addWhereEqualTo("questionType", id1);
                    bmobQuery.setLimit(200);
                    bmobQuery.findObjects(new FindListener<Question>() {
                        @Override
                        public void done(List<Question> list, BmobException e) {
                            if (e != null || list == null || list.size() == 0){
                                allQuestionView.setText("本题库共0题");
                                ToastUtils.showLong("本次未获取到题库，请联系管理员L2B！");
                                progressDialog.dismiss();
                                progressDialog.cancel();
                                if (list.size() > 0){
                                    isHaveQuestion = true;
                                    LogUtils.i(2 + " true");
                                }else {
                                    isHaveQuestion = false;
                                    LogUtils.i(2 + " false");
                                }
                                return;
                            }
                            int sum = 0;
                            for (Question question : list) {
                                ContentValues values = new ContentValues();
                                values.put("objectId", question.getObjectId());
                                values.put("_index", question.getIndex());
                                values.put("type", question.getType());
                                values.put("typeIndex", question.getTypeIndex());
                                values.put("questionType", question.getQuestionType());
                                values.put("title", question.getTitle());
                                values.put("aOption", question.getaOption());
                                values.put("bOption", question.getbOption());
                                values.put("cOption", question.getcOption());
                                values.put("dOption", question.getdOption());
                                values.put("answer", question.getAnswer());
                                values.put("analysis", question.getAnalysis());
                                long tb_question = daoInstant.insert("tb_question", null, values);
                                if (tb_question <= 0){
                                    sum++;
                                }
                            }
                            allQuestionView.setText("本题库共" + list.size() + "题");
                            ToastUtils.showLong("本次获取到 " + list.size() + " 题 " + sum + " 道题目加载异常！");
                            if (list.size() > 0){
                                isHaveQuestion = true;
                                LogUtils.i(2 + " true");
                            }else {
                                isHaveQuestion = false;
                                LogUtils.i(2 + " false");
                            }
                            progressDialog.dismiss();
                            progressDialog.cancel();
                        }
                    });

                }else {
                    allQuestionView.setText("本题库共" + cursor.getCount() + "题");
                    if (cursor.getCount() > 0){
                        isHaveQuestion = true;
                        LogUtils.i(3 + " true");
                    }else {
                        isHaveQuestion = false;
                        LogUtils.i(3 + " false");
                    }
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }

    @Override
    void initListener() {
        super.initListener();

    }
}